﻿#region Copyright 
/*-------------------------------------------------------------------------
* 命名空间名称/文件名:    SSPivot.Admin.Core.Middlewares/ExceptionHandlerMiddware 
* CLR版本:     4.0.30319.42000
* 机器名称:    DESKTOP-NHMLO8A
* 功 能：       N/A
* 类 名：       ExceptionHandlerMiddware
* 创建时间：  2025/5/23 18:54:01
* 版本号：      v1.0
* 创建人:        xulong
*-------------------------------------------------------------------------*/
#endregion
using Microsoft.AspNetCore.Http;
using SSPivot.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace SSPivot.Admin.Core.Middlewares
{
    /// <summary>
    /// 异常错误统一返回记录
    /// </summary>
    public class ExceptionHandlerMiddware
    {
        private readonly RequestDelegate _next;

        public ExceptionHandlerMiddware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        private async Task HandleExceptionAsync(HttpContext context, Exception ex)
        {
            if (ex == null) return;
            Serilog.Log.Error($"----------\r\n Web全局捕获异常\r\nMessage:{ex.Message}:Trace:{ex.StackTrace}");
            await WriteExceptionAsync(context, ex).ConfigureAwait(false);
        }

        private static async Task WriteExceptionAsync(HttpContext context, Exception e)
        {
            if (e is UnauthorizedAccessException) context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            else if (e is Exception) context.Response.StatusCode = (int)HttpStatusCode.BadRequest;

            context.Response.ContentType = "application/json";
            var result = ServiceResult.Fail($"全局捕获异常:{e.Message}", e.StackTrace);
            await context.Response.WriteAsync(result.SerializeJson()).ConfigureAwait(false);
        }
    }
}
